class Solution
{
public:
    vector<long long> distance(vector<int> &nums)
    {
        unordered_map<int, vector<long long>> indices;
        int n = nums.size();
        for (int i = 0; i < n; ++i)
        {
            indices[nums[i]].push_back(i);
        }

        unordered_map<int, vector<long long>> indicesPrefixSum;
        for (auto &[num, numIndices] : indices)
        {
            indicesPrefixSum[num] = vector<long long>(numIndices.size() + 1, 0);
            partial_sum(numIndices.begin(), numIndices.end(), indicesPrefixSum[num].begin() + 1);
        }

        vector<long long> result(n, 0);
        for (auto &[num, numIndices] : indices)
        {
            auto &numIndicesPrefixSum = indicesPrefixSum[num];

            int indicesSize = numIndices.size();
            for (int i = 0; i < indicesSize; ++i)
            {
                long long curIndex = numIndices[i];
                long long frontIndicesSum = numIndicesPrefixSum[i];
                long long backIndicesSum = numIndicesPrefixSum[indicesSize] - numIndicesPrefixSum[i + 1];
                long long frontIndicesCount = i;
                long long backIndicesCount = indicesSize - i - 1;
                result[curIndex] = curIndex * frontIndicesCount - frontIndicesSum + backIndicesSum - curIndex * backIndicesCount;
            }
        }
        return result;
    }
};